<template>
  <div class="club-container">
    <!-- 头部区域 -->
    <div class="club-header">
      <div class="header-content">
        <div class="logo-container logo-wrapper">
          <img class="club-logo" :src="clobsData.logo" alt="社团logo" />
        </div>
        <div class="club-info">
          <h1 class="club-title">{{ clobsData.name }}</h1>
          <p class="club-description">{{ clobsData.description }}</p>
          <div class="action-buttons">
            <el-button type="primary" @click="open" v-if="currentJoinForm.length === 0">
              申请加入
            </el-button>
            <el-button plain @click="getJoinFormByToken(false)">
              报名结果
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 申请加入表单 -->
    <el-dialog :append-to-body="true" title="欢迎报名" :visible.sync="dialogVisible" width="30%" :before-close="handleClose"
      center>
      <el-form label-width="100px" :model="form">
        <!-- 新增：顶部提示标语 -->
        <el-form-item>
          <p style="color: #f56c6c; font-size: 14px; margin-bottom: 15px;">
            ⚠️提示：每个社团每人仅能报名一次，请认真填写信息
            若无法提交表单，请检查登录状态
          </p>
        </el-form-item>
        <el-form-item label="姓名" required>
          <el-input v-model="form.name" :disabled="labelDisable"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="form.gender" required :disabled="labelDisable">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="学院" required>
          <el-select filterable v-model="form.collegeId" placeholder="请选择学院" @change="colleageChanged(form.collegeId)"
            :disabled="labelDisable">
            <el-option v-for="(item, index) in collegeAndMajor" :key="index" :label="item.collegeName"
              :value="item.collegeId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专业" required>
          <el-select v-model="form.majorId" placeholder="请选择专业" :disabled="labelDisable">
            <el-option filterable v-for="(item, index) in majorList" :key="index" :label="item.name"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" required>
          <el-select v-model="form.deptId" placeholder="请选择部门" :disabled="labelDisable">
            <el-option filterable v-for="(item, index) in deptsList" :key="index" :label="item.name"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" required>
          <el-input v-model="form.phone" :disabled="labelDisable"></el-input>
        </el-form-item>
        <el-form-item label="个人描述" required>
          <el-input v-model="form.description" :disabled="labelDisable"></el-input>
        </el-form-item>
        <el-form-item>
          <!-- 仅当 labelDisable 为 false（可编辑状态）时显示提交按钮 -->
          <el-button type="primary" @click="addJoinForm(form)" v-if="!labelDisable">
            提交
          </el-button>
          <el-button @click="dialogVisible = false" v-else>取消</el-button>

          <!-- 已报名时显示状态标签 -->
          <template v-if="labelDisable">
            <!-- status=0：未处理（中性蓝色标签） -->
            <el-tag type="info" v-if="form.status === 0">
              您的报名申请正在处理中，请耐心等待审核结果
            </el-tag>
            <!-- status=1：已录取（成功绿色标签） -->
            <el-tag type="success" v-else-if="form.status === 1">
              恭喜您已被录取！
            </el-tag>
            <!-- status=2：未通过（危险红色标签） -->
            <el-tag type="danger" v-else>
              非常遗憾，您没有被录取！
            </el-tag>
          </template>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 内容区域 -->
    <div class="content-section">
      <!-- 热门公告 -->
      <div class="content-card">
        <h2 class="section-title"><span class="icon">📢</span> 热门公告</h2>
        <div class="announcement-list">
          <div v-for="(e, i) in announcementList" :key="i" class="announcement-item" @click="goNoticeDetails(e)">
            <div class="announcement-tags">
              <span class="tag type-tag">{{
                e.type === "0" ? "公告" : "活动"
              }}</span>
              <span v-if="e.isTop" class="tag top-tag">置顶</span>
            </div>
            <div class="announcement-content">
              <h3 class="announcement-title">{{ e.title }}</h3>
              <span class="announcement-time">{{
                e.gmtCreate.substr(0, 16)
              }}</span>
            </div>
          </div>
          <div v-if="!announcementList.length" class="empty-state">
            <p>暂无公告信息</p>
          </div>
        </div>
        <pagination class="pagination" v-show="clobsAnnouncementQueryData.total > 0"
          :total="clobsAnnouncementQueryData.total" :page.sync="clobsAnnouncementQueryData.pageNum"
          :limit.sync="clobsAnnouncementQueryData.pageSize" @pagination="getAnnouncementList" />
      </div>

      <!-- 社团部门 -->
      <div class="content-card">
        <h2 class="section-title"><span class="icon">🏛️</span> 社团部门</h2>
        <div class="department-grid">
          <div v-for="(e, i) in deptData" :key="i" class="department-item" @click="openDetails(e.id, e.name)">
            {{ e.name }}
          </div>
        </div>
        <div v-if="!deptData.length" class="empty-state">
          <p>暂无部门信息</p>
        </div>
      </div>

      <!-- 优秀成员 -->
      <div class="content-card">
        <h2 class="section-title">
          <span class="icon">🏆</span> 优秀教师/成员
        </h2>
        <div class="member-list">
          <div v-for="(e, i) in teacherData" :key="i" class="member-card">
            <img class="member-avatar" :src="e.image" alt="头像" />
            <div class="member-info">
              <h3 class="member-name">{{ e.name }}</h3>
              <p class="member-title">{{ e.title }}</p>
              <p class="member-desc">{{ e.description }}</p>
            </div>
          </div>
          <div v-if="!teacherData.length" class="empty-state">
            <p>暂无成员信息</p>
          </div>
        </div>
      </div>

      <!-- 活动信息 -->
      <div class="content-card">
        <h2 class="section-title"><span class="icon">🎯</span> 社团活动</h2>
        <div class="activity-list">
          <activitie v-for="(e, i) in activityData" :data="e" :key="i" class="activity-item" />
        </div>
        <div v-if="!activityData.length" class="empty-state">
          <p>暂无活动信息</p>
        </div>
        <pagination class="pagination" v-show="activityQueryData.total > 0" :total="activityQueryData.total"
          :page.sync="activityQueryData.pageNum" :limit.sync="activityQueryData.pageSize"
          @pagination="getActivityLists" />
      </div>
    </div>

    <el-dialog title='部门详细信息' :visible.sync="departmentDetailsVisible" width="40%">
      <div>
        <div class="deptDetailTop">
          <div style="width: 40%;"><img :src="deptDetailData.image" alt="" style="width: 100%;" /></div>
          <div class="deptDetailSummary">
            <p class="deptDetailTitle">{{ deptName }}</p>
            <p class="fs-16">{{ deptDetailData.brief }}</p>
          </div>
        </div>
        <div class="fs-16">{{ deptDetailData.description }}</div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cencle">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>


<script>
import { selectId } from "@/api/organizations/index.js";
import {
  addJoinForm,
  getJoinFormByToken,
  delJoinFormByToken,
} from "@/api/signUp.js";
import {
  getAnnouncementLists,
  getDeptByPage,
  getTeacher,
  getActivityLists,
  getAllActivityList,
} from "@/api/cms/cms.js";
import {
  queryDepts,
  queryDeptDetail,
} from "@/api/departmentalServices/department.js";
import Pagination from "@/components/Pagination/index.vue";
import Activitie from "@/components/Activitie/index.vue";

export default {
  components: {
    Pagination,
    Activitie,
  },
  asyncData({ query }) {
    // 返回一个对象，其中包含了从上下文(query)中获取的noticeId
    // 这个noticeId将被用作组件的一个属性，可以在组件的模板或方法中使用
    return {
      noticeId: query.id,
    };
  },
  data() {
    return {
      departmentDetailsVisible: false, //是否打开部门详细对话框
      deptDetailData: {}, //部门详细信息
      deptName: "", //部门名称
      clobsData: {},
      announcementList: [],
      collegeAndMajor: [], //学院信息
      majorList: [], //专业信息
      deptsList: [], //部门信息
      dialogVisible: false, //是否打开对话框
      labelDisable: false, //表单标签位置
      clobsAnnouncementQueryData: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      deptData: [],
      deptQueryData: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      teacherData: [],
      teacherQueryData: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      activityData: [],
      activityQueryData: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      joinForm: [],
      deptOptions: [],
      form: {
        //申请加入表单
        name: "",
        collegeId: "",
        clubId: "",
        deptId: "",
        majorId: "",
        gender: 0,
        phone: "",
        description: "",
        status: 0, // 初始化状态，可根据实际需求调整
      },

      loading: false, // 用于控制加载状态
      hasJoinedCurrentClub: false, // 是否报名了当前社团

      globalJoinForm: [], // 用户所有社团的报名记录（未筛选）
      currentJoinForm: [], // 当前社团的报名记录（筛选后）

    };
  },
  created() {
    this.selectId();
    this.getAnnouncementList();
    this.getDeptByPage();
    this.getTeacher();
    this.getJoinFormByToken(true);
    this.getActivityLists();
    this.getColInfo();
    this.getDepts();
  },
  methods: {
    open() {
      this.dialogVisible = true;
      // 初始化表单为“未报名”状态
      this.form = {
        name: "",          // 可根据用户信息自动填充（若有）
        gender: 0,         // 男
        collegeId: "",     // 学院ID
        majorId: "",       // 专业ID
        deptId: "",        // 部门ID
        phone: "",         // 联系电话
        description: "",   // 个人描述
        status: 0,         // 关键：标记为“未报名”状态，显示提交按钮
        clubId: this.noticeId, // 关联当前社团ID
      };
      this.labelDisable = false; // 确保表单可编辑
    },
    handleClose(done) {
      done();
      // this.$confirm('确认关闭？')
      //   .then(_ => {
      //     done();
      //   })
      //   .catch(_ => { });
    },
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    selectId() {
      selectId(this.noticeId).then((res) => {
        this.clobsData = res.data.JoinClubs;
      });
    },
    async addJoinForm(formData) {
      const res = await addJoinForm(formData);
      if (res.code === 20000) {
        this.$message.success("报名成功！");
        this.dialogVisible = false;
        // 重新查询报名记录，更新 currentJoinForm
        await this.getJoinFormByToken(true);
      } else {
        this.$message.error("报名失败，请重试");
      }
    },
    colleageChanged(value) {
      for (let i = 0; i < this.collegeAndMajor.length; i++) {
        if (this.collegeAndMajor[i].collegeId === value) {
          this.majorList = this.collegeAndMajor[i].majorList;
          this.form.majorId = "";
        }
      }
    },
    getColInfo() {
      //获取学院信息
      this.$store
        .dispatch("queryCollege")
        .then(() => {
          this.collegeAndMajor = this.$store.state.collegeAndMajor;
          for (let i = 0; i < this.collegeAndMajor.length; i++) {
            if (this.collegeAndMajor[i].collegeId === this.form.collegeId) {
              this.majorList = this.collegeAndMajor[i].majorList;
            }
          }
        })
        .catch((error) => {
          console.error("获取学院专业列表失败", error);
        });
    },
    getDepts() {
      //获取部门信息
      queryDepts(this.noticeId).then((res) => {
        if (res.code === 20000) {
          console.log("111", res);
          this.deptsList = res.data.depts;
        } else {
          console.log(res);
        }
      });
    },

    // 修改查询报名结果的方法，处理状态为0（未处理）的情况
    async getJoinFormByToken(flag) {
      try {
        const res = await getJoinFormByToken({ clubId: this.noticeId });
        if (res.code === 20000) {
          // 保存用户所有报名记录（未筛选）
          this.globalJoinForm = Array.isArray(res.data.joinForm) ? res.data.joinForm : [];
          // 筛选当前社团的报名记录（强类型匹配）
          this.currentJoinForm = this.globalJoinForm.filter(
            (item) => String(item.clubId) === String(this.noticeId)
          );

          // 更新表单状态
          if (this.currentJoinForm.length > 0) {
            // 有当前社团报名记录 → 禁用提交
            this.form = { ...this.currentJoinForm[0] }; // 使用解构赋值避免直接引用
            this.labelDisable = true;

            // 根据状态给出相应提示（整合状态文本映射，统一管理）
            const statusTextMap = {
              0: "您的报名申请已经提交至审核，请耐心等待结果", // 未处理
              1: "恭喜您已通过审核，已被录取！",                 // 已录取
              2: "很遗憾，您未通过审核，没有被录取"               // 未通过
            };
            this.$message.info(statusTextMap[this.form.status] || "您的报名状态未知");
          } else {
            // 无当前社团报名记录 → 允许提交
            this.form = {
              name: "",
              gender: 0,
              collegeId: "",
              majorId: "",
              deptId: "",
              phone: "",
              description: "",
              status: 0,
              clubId: this.noticeId,
            };
            this.labelDisable = false;
          }

          // 控制弹窗显示
          if (!flag) {
            this.dialogVisible = true;

            // 状态提示优化（与上方状态文本保持一致）
            if (this.currentJoinForm.length > 0) {
              const statusTextMap = {
                0: "您的报名申请正在处理中，请耐心等待审核结果",
                1: "恭喜您已通过报名审核，已被录取",
                2: "很遗憾，您未通过报名审核，没有被录取"
              };
              this.$message.info(statusTextMap[this.form.status] || "您的报名状态未知");
            } else if (this.globalJoinForm.length > 0) {
              this.$message.info("您已报名其他社团，可报名当前社团");
            }
          }
        } else {
          this.$message.error(`查询失败：${res.message || '未知错误'}`);
        }
      } catch (error) {
        this.$message.error("查报名记录失败，请检查登录或网络后重试");
        console.error("查询报名记录错误：", error);
      }
    },
    goNoticeDetails(e) {
      this.$router.push(`/noticeDetails?id=${e.id}`);
    },
    getAnnouncementList() {
      this.announcementList = [];
      getAnnouncementLists(
        this.clobsAnnouncementQueryData.pageNum,
        this.clobsAnnouncementQueryData.pageSize,
        { clubId: this.noticeId }
      ).then((res) => {
        if (res.code == 20000) {
          this.announcementList = res.data.list.records;
          this.clobsAnnouncementQueryData.total = res.data.list.total;
        }
      });
    },
    getDeptByPage() {
      getDeptByPage(1, 999999, { clubId: this.noticeId }).then((res) => {
        if (res.code == 20000) {
          this.deptData = res.data.list.records;
          this.deptQueryData.total = res.data.list.total;
        }
      });
    },
    getTeacher() {
      getTeacher(1, 999999, { clubId: this.noticeId }).then((res) => {
        if (res.code == 20000) {
          this.teacherData = res.data.list.records;
          this.teacherQueryData.total = res.data.list.total;
        }
      });
    },
    getActivityLists() {
      // getAllActivityList(this.activityQueryData.pageNum, this.activityQueryData.pageSize, {  }).then(res => {
      getActivityLists(
        this.activityQueryData.pageNum,
        this.activityQueryData.pageSize,
        { clubId: this.noticeId }
      ).then((res) => {
        if (res.code == 20000) {
          this.activityData = res.data.list.records;
          this.activityQueryData.total = res.data.list.total;
          // this.activityData = res.data.list
        }
      });
    },
    delJoinFormByToken() {
      delJoinFormByToken().then((res) => { });
    },

    //打开部门详细对话框
    async openDetails(id, name) {
      await queryDeptDetail(id).then((res) => {
        this.deptName = name;
        this.deptDetailData = res.data.deptDetail;
      });
      this.departmentDetailsVisible = true;
    },
    //关闭弹窗
    cencle() {
      this.departmentDetailsVisible = false;
      this.deptDetailData = {};
      this.deptName = "";
    },
  },
};
</script>

<style scoped>
/* 基础样式 */
.club-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  box-sizing: border-box;
  min-width: 500px;
}

/* 头部样式 */
.club-header {
  background: linear-gradient(135deg, #52c1f0 0%, #034386 100%);
  border-radius: 12px;
  padding: 30px;
  margin-bottom: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  align-items: center;
  gap: 40px;
}

.logo-wrapper {
  flex-shrink: 0;
  width: 200px;
  height: 200px;
  border-radius: 50%;
  overflow: hidden;
  border: 4px solid white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.club-logo {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.club-info {
  color: white;
}

.club-title {
  font-size: 2.2rem;
  margin: 0 0 15px 0;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
}

.button-group {
  display: flex;
  gap: 15px;
  margin-top: 20px;
}

/* 内容区域样式 */
.content-section {
  display: grid;
  gap: 24px;
}

.content-card {
  background: white;
  border-radius: 16px;
  padding: 22px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 20px;
  color: #1e293b;
  margin: 0 0 24px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding-bottom: 10px;
  border-bottom: 2px solid #3db0e0;
}

.icon {
  font-size: 24px;
}

/* 公告列表样式 */
.announcement-list {
  display: grid;
  gap: 12px;
}

.announcement-item {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #f8fafc;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.announcement-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.announcement-tags {
  flex: 0 0 120px;
  display: flex;
  gap: 8px;
}

.tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.type-tag {
  background: #bfdbfe;
  color: #1d4ed8;
}

.top-tag {
  background: #fecaca;
  color: #dc2626;
}

.announcement-content {
  flex: 1;
}

.announcement-title {
  margin: 0;
  font-size: 16px;
  color: #1e293b;
}

.announcement-time {
  font-size: 12px;
  color: #94a3b8;
}

/* 部门网格样式 */
.department-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 12px;
}

.department-item {
  padding: 16px;
  background: #f8fafc;
  border-radius: 8px;
  text-align: center;
  transition: all 0.2s;
}

.department-item:hover {
  background: #e2e8f0;
}

/* 成员卡片样式 */
.member-list {
  display: grid;
  gap: 16px;
}

.member-card {
  display: flex;
  gap: 16px;
  padding: 16px;
  background: #f8fafc;
  border-radius: 8px;
}

.member-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #e2e8f0;
}

.member-info {
  flex: 1;
}

.member-name {
  margin: 0 0 8px;
  font-size: 16px;
  color: #1e293b;
}

.member-title {
  color: #3b82f6;
  margin: 0 0 4px;
  font-size: 14px;
}

.member-desc {
  color: #64748b;
  margin: 0;
  font-size: 14px;
}

.activity-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 12px;
}

/* 空状态样式 */
.empty-state {
  padding: 32px;
  text-align: center;
  color: #94a3b8;
}

.pagination {
  margin-top: 10px;
  text-align: right;
}

/* 组件样式 */
.activitie-box {
  width: 100%;
  box-sizing: border-box;
  padding: 5px 1%;
  background-color: #f8fafc;
  display: inline-block;
}

::v-deep .activitie-title {
  font-size: 26px;
}

::v-deep .flex {
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    padding: 24px;
  }

  .club-title {
    font-size: 1.8rem;
  }

  .logo-wrapper {
    width: 150px;
    height: 150px;
  }

  .logo-container {
    width: 150px;
    height: 150px;
  }

  .action-buttons {
    position: static;
    margin-top: 24px;
    justify-content: center;
  }

  .content-card {
    padding: 14px;
  }
}

.deptDetailTop {
  display: flex;
  flex-direction: row;
}

.deptDetailSummary {
  margin-left: 10px;
}

.deptDetailTitle {
  font-size: 20px;
}

.fs-16 {
  font-size: 16px;
}

p {
  margin: 0;
}
</style>
